//
//  UserAPI.swift
//  Employee
//
//  Created by swordjoy on 2017/3/16.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import Foundation
import Moya
import MBProgressHUD
import Alamofire

class DefaultAlamofireManager: Manager {
  
    static let sharedManager: DefaultAlamofireManager = {
        let configuration = URLSessionConfiguration.default
        configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        configuration.timeoutIntervalForRequest = 15 // as seconds, you can set your request timeout
        configuration.timeoutIntervalForResource = 15 // as seconds, you can set your resource timeout
        configuration.requestCachePolicy = .useProtocolCachePolicy
        return DefaultAlamofireManager(configuration: configuration)
    }()
  
}

let UserendpointClosure = { (target: UserAPI) -> Endpoint<UserAPI> in
  let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
  return defaultEndpoint.adding(newHTTPHeaderFields: ["X-Requested-With": "XMLHttpRequest", "User-Agent": "iOS", "Cookie": Cookie.cookie])
}


let UserProvider = MoyaProvider<UserAPI>(
    endpointClosure: UserendpointClosure,
        manager: DefaultAlamofireManager.sharedManager,
        plugins:[
            NetworkLoggerPlugin(verbose: true)
        ]
)

public enum UserAPI {
    case login(username: String, password: String)
    case refreshToken()
    case getUserInfo()
    case getUserAddressBook()
    case logout()
    case getModifyPasswordCode(phone: String)
    case verifyCode(phone: String, code: String)
    case resetPassword(phone: String, password: String)
    case setPushAlias()
    case getVersion
}

extension UserAPI: TargetType {
  
    /// The path to be appended to `baseURL` to form the full `URL`.
    public var path: String {
        switch self {
            case .login:
            return "/oauth2/token"
            case .refreshToken:
            return "/oauth2/token"
            case .getUserInfo:
            return "/ms/v\(SJApp.version)/currentStaff.json"
            case .getUserAddressBook:
            return "/ms/v\(SJApp.version)/list.json"
            case .logout:
            return "/logout.htm"
            case .getModifyPasswordCode:
            return "/mi/v\(SJApp.version)/getSMSVerificationCode.json"
            case .verifyCode:
            return "/mi/v\(SJApp.version)/checkIsCorrectCode.json"
            case .resetPassword:
            return "/mi/v\(SJApp.version)/resetPassWord.json"
            case .setPushAlias:
            return "/ms/v\(SJApp.version)/setPushAlias.json"
            case .getVersion:
            return "/mi/app/update/ios.json"
        }
    }
  
  
  /// The parameters to be incoded in the request.
  public var parameters: [String : Any]? {
    switch self {
      case let .login(username, password):
        return ["client_id": "824bce609110472a9dcf837ada0053e1", "client_secret": "2692e5ef9dc34482b5993a311f086090", "grant_type": "password", "scope": "servicecenter", "username": username, "password": password].signParame(GlobalConfig.privateKey)
      case .refreshToken():
        return ["client_id": "824bce609110472a9dcf837ada0053e1", "client_secret": "2692e5ef9dc34482b5993a311f086090", "grant_type": "refresh_token", "refresh_token": Token.shared.refreshToken].signParame(GlobalConfig.privateKey)
      case .getUserInfo:
        return ["access_token": Token.shared.token].signParame(GlobalConfig.privateKey)
      case .getUserAddressBook:
        return ["access_token": Token.shared.token, "page.pn": "1", "page.size": "1000"].signParame(GlobalConfig.privateKey)
      case .logout:
        return ["access_token": Token.shared.token].signParame(GlobalConfig.privateKey)
      case let .getModifyPasswordCode(phone):
        return ["mobile": phone].signParame(GlobalConfig.privateKey)
      case let .verifyCode(phone, code):
        return ["mobile": phone, "code": code].signParame(GlobalConfig.privateKey)
      case let .resetPassword(phone, password):
        return ["mobile": phone, "password": password].signParame(GlobalConfig.privateKey)
      case .setPushAlias:
        return ["access_token": Token.shared.token, "pushAlias": JPUSHService.registrationID()!].signParame(GlobalConfig.privateKey)
      case .getVersion:
        return ["appType":"WORKORDER_APP", "version":SJApp.version].signParame(GlobalConfig.privateKey)
    }
  }
  
  /// The target's base `URL`.
  public var baseURL: URL {
    switch self {
      case .login, .refreshToken:
        return URL(string: GlobalConfig.BASE_URL)!
    default:
      return URL(string: GlobalConfig.BASE_OUT_URL)!
    }
  }
  
  /// The HTTP method used in the request.
  public var method: Moya.Method {
    switch self {
      case .login, .refreshToken:
        return .post
      case .resetPassword, .setPushAlias():
        return .put
    default: return .get
    }
  }
  
  public var task: Task { return .request }
  
  /// The method used for parameter encoding.
  public var parameterEncoding: ParameterEncoding { return URLEncoding.default }
  
  // 测试使用,暂时用不上
  public var sampleData: Data { return Data() }
}
